﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Labthink.PCSoft.UniversalHost4.DataAccess;
using Labthink.PCSoft.UniversalHost4.Model.User;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;
using Application = System.Windows.Application;
using Button = System.Windows.Controls.Button;
using Control = System.Windows.Controls.Control;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    public partial class UcRoleManage
    {
        private NotifyManager _notify;
        private int _count;


        public UcRoleManage()
        {
            DataContext = this;
            InitializeComponent();
            Title = LanguageManager.GetLanguageValue("RoleMgmtWindowTitle");
        }

        public ObservableCollection<Role> Roles { get; } =
           new ObservableCollection<Role>(new List<Role>());

        public string Title { get; set; }

        public string PermissionCode { get; set; } = "Per_RoleMgmt";

        void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = string.Format("{0,2}", e.Row.GetIndex() + 1);
            //Task.Run(() =>
            //{
            //    Thread.Sleep(50);
            //    Dispatcher?.Invoke(() =>
            //    {
            //        var txt = dgRoles.Columns[0].GetCellContent(e.Row) as TextBlock;
            //        while (txt == null)
            //        {
            //            Thread.Sleep(50);
            //            txt = dgRoles.Columns[0].GetCellContent(e.Row) as TextBlock;
            //        }
            //        txt.Text = (_count - e.Row.GetIndex()) + "";
            //    });
            //});
        }

        private void btnModify_Click(object sender, RoutedEventArgs e)
        {
            var role = ((Button)sender).CommandParameter as Role;
            if (role == null) return;
            var mr = new AddRole { RoleId = role.Id };
            var r = mr.ShowDialog(Application.Current.MainWindow);
            if (r.HasValue && r.Value)
            {
                _notify.ShowSuccess(mr.ActionMsg);
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var role = ((Button)sender).CommandParameter as Role;
            if (role == null) return;
            var r = LanguageManager.GetLanguageValue("Confirm_DelRole", role.Name);
            if (MyMessageBox.Show(Window.GetWindow(this), r, MyMessageBoxButton.OkCancel, MyMessageBoxImage.Warning, MyMessageBoxDefaultButton.Ok) != MyMessageBoxResult.Ok) return;
            try
            {
                RoleAndPerRepository.DeleteRole(role.Id);
                LogRepository.AddLog(LanguageManager.GetLanguageValue("OP-RoleDelete", role.Id), "Manage");
                _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
                GetRoles();
            }
            catch (Exception ex)
            {
                _notify.ShowError(ex.Message);
            }
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            var ar = new AddRole();
            var r = ar.ShowDialog(Application.Current.MainWindow);
            if (r.HasValue && r.Value)
            {
                _notify.ShowSuccess(ar.ActionMsg);
                GetRoles();
            }
        }

        private void Control_OnLoaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            var w = Window.GetWindow(this);
            _notify = NotifyManager.InstanceManager(w);

            DataContext = Roles;
            LoadData.Visibility = Visibility.Collapsed;
            GetRoles();
        }

        private void GetRoles()
        {
            ShowLoading();

            // 方便配置Administrator和Admin的权限
            bool includeHidden = Debugger.IsAttached;
            List<Role> roles = RoleAndPerRepository.GetRoles(includeHidden);

            Roles.Clear();
            foreach (Role rr in roles)
            {
                Roles.Add(rr);
            }

            _count = Roles.Count;
            dgRoles.ItemsSource = Roles;
            HideLoading();
        }

        private void LoadData_OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var isEnabled = sender is Loading loading && loading.Visibility == Visibility.Collapsed;
            var controls = new List<Control>
            {
                btnAdd,
            };

            foreach (var c in controls)
            {
                c.IsEnabled = isEnabled;
            }
        }

        private void ShowLoading()
        {
            LoadData.Visibility = Visibility.Visible;
        }

        private void HideLoading()
        {
            LoadData.Visibility = Visibility.Collapsed;
        }
    }
}
